<template>
    <a-form :model="form" name="form" layout="vertical" :rules="rules" autocomplete="off" @submit="submit">
        <a-form-item label="用户名" name="username">
            <a-input size="large" v-model:value="form.username" />
        </a-form-item>

        <a-form-item label="密码" name="password">
            <a-input-password size="large" v-model:value="form.password" />
        </a-form-item>

        <a-form-item label="验证码" name="code">
            <div class="code_box">
                <a-input size="large" style="margin-right: 10px;" v-model:value="form.code" />
                <IdentifyCode @updateIdentifyCode="setIdentifyCode" />
            </div>
        </a-form-item>

        <a-form-item>
            <a-button type="primary" class="primary_btn" style="width:100%" size="large" html-type="submit">登 录</a-button>
        </a-form-item>
    </a-form>
</template>
<script setup lang="ts">
import { reactive } from 'vue'
import IdentifyCode from '@/components/identify-code/index.vue'
import { Form, message } from 'ant-design-vue';
import { ILogin } from '../login.types'
import { rules } from './rules.ts'
import { loginByUsername } from '@/api/common';
import userStore from '@/store/user';
import settingStore from '@/store/setting';
//表单
let form = reactive<ILogin>({
    username: 'chenchuang',
    password: '123456',
    code: ''
});
//验证码暂存
let codeInfo = '';
//提交
const useForm = Form.useForm;
const { validate } = useForm(form, rules);
const submit = () => {
    validate().then(async () => {
        let data = toRaw(form);
        let { code } = data;
        if (code.toLowerCase() != codeInfo.toLowerCase()) {
            message.error('验证码错误');
            return false;
        }
        const settingInfo = settingStore();
        settingInfo.updateLoading();
        try {
            let res = await loginByUsername(data);
            let { token,userInfo } = res.data;
            let userModel = userStore();
            userModel.updateToken(token as string);
            userModel.updateUserInfo(userInfo);
            message.success('登录成功')
            setTimeout(() => {
                window.location.replace('/middleware');
            }, 500)
        } finally {
            settingInfo.resetLoading();
        }
    }).catch(err => {
        console.log(err)
    })
}
// 验证码更新
const setIdentifyCode = (value: string) => {
    form.code = value;
    codeInfo = value
}
</script>
<style lang="scss" scoped>
.code_box {
    display: flex;
    align-items: center;
}
</style>